#include <iostream>
#include <pthread.h>
#include <cstring>
#include <unistd.h>
#include <vector>

#define NUM 3
using namespace std;

class mythread
{
public:
    string name_;
    mythread(string name) : name_(name)
    {
    }
};
string tohex(pthread_t tid)
{
    char buffer[128];
    snprintf(buffer, sizeof(buffer), "0x%x", tid);
    return buffer;
}
__thread int test_i = 0; // 线程局部存储
void *runfunc(void *args)
{
    // int test_i = 0; // 每个线程有自己独立的栈结构
    mythread *td = static_cast<mythread *>(args);
    int cnt = 0;
    while (cnt)
    {
        cout << td->name_ << ", pid: " << getpid() << ", tid" << tohex(pthread_self()) << ",test-i:"
             << test_i << ",&test_i:" << tohex((pthread_t)&test_i) << endl;
        cnt++;
        test_i++;
        sleep(1);
    }
    delete td;
    return NULL;
}

int main()
{
    vector<pthread_t> tids;
    for (int i = 0; i < NUM; i++)
    {
        mythread *td = new mythread("thread -" + to_string(i));
        pthread_t tid;
        pthread_create(&tid, NULL, runfunc, td);
        tids.push_back(tid);
        sleep(1);
    }
    // pthread_exit(NULL);
    for (int i = 0; i < tids.size(); i++)
    {
        pthread_join(tids[i], NULL);
    }

    return 0;
}